import {clearLogin} from '@/api/auth.js'
let baseUrl="http://localhost/dev-api/";
let version = __wxConfig.envVersion;
if(version==="develop"){
	baseUrl="http://localhost/dev-api/";
}else if(version==="trial"){
	baseUrl="https://www.sanfayin.cn/prod-api/";
}else if(version==="release"){
	baseUrl="https://www.sanfayin.cn/prod-api/";
}
module.exports=(vm)=>{
	// 初始化请求配置：config 为默认设置
	uni.$u.http.setConfig((config)=>{
		config.baseURL=baseUrl;
		 config.header={
			 'content-type':'application/json;charset=UTF-8',
		 };
		 config.method='GET';
		 config.dataType='json';
		 config.timeout=60000;
		 return config;
	});
	
	//请求拦截
	uni.$u.http.interceptors.request.use((config)=>{
		uni.showLoading({
			title:"请稍后....",
			mask:true
		});
		config.data=config.data||{};
		//设置token
		console.log("getToken from storage",uni.getStorageSync('token'));
		const token=uni.getStorageSync('token') || '';
		console.log("发送请求，设置token",uni.getStorageSync("token"));
		config.header['token']=token;
		return config;
	},config=>{
		uni.$u.toast("连接服务器失败");
		return Promise.reject(config);
	});
	
	//响应拦截
	uni.$u.http.interceptors.response.use((response)=>{
		uni.hideLoading();
		const ajaxData=response.data;
		if(!ajaxData){
			uni.$u.toast("请求失败，网络错误。");
			return false;
		}
		const code=ajaxData.code;
	
		if(code==200){
			return ajaxData;
		}else if(code===-777){
			clearLogin();
			//如果token解析错误，则跳转到登录页面
			uni.navigateTo({
				url:'/pages/login/Login'
			})
		}else if(code===-666){
			clearLogin();
			uni.navigateTo({
				url:'/pages/login/Login'
			})
		}
		else{
			uni.$u.toast(ajaxData.msg);
			return Promise.reject('error')
			
		}
		
	},
	error => {
		uni.hideLoading();
	    console.log('err' ,error.errMsg);
	    let errMsg = error.errMsg;
		
	    if (errMsg ==="request:fail ") {
	      errMsg = "后端接口连接异常";
	    } else{
	      errMsg = "系统接口请求超时";
	    }
		uni.showToast({
			icon:"error",
			title:errMsg
		});
	   
	    return Promise.reject(error);
	  }
	
	)
}
